package cn.itsource.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.itsource.constants.Constants;
import cn.itsource.desktop.api.LoginApi;
import cn.itsource.desktop.pojo.param.LoginUpdate;
import cn.itsource.pojo.domain.Driver;
import cn.itsource.pojo.domain.DriverAuthMaterial;
import cn.itsource.mapper.DriverAuthMaterialMapper;
import cn.itsource.pojo.dto.AuditParamDto;
import cn.itsource.pojo.dto.AuthApplyMaterialDto;
import cn.itsource.result.JSONResult;
import cn.itsource.service.IDriverAuthMaterialService;
import cn.itsource.service.IDriverMaterialAuthLogService;
import cn.itsource.service.IDriverService;
import cn.itsource.utils.AssertUtil;
import cn.itsource.utils.BitStatesUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 司机实名资料 服务实现类
 * </p>
 *
 * @author ????
 * @since 2024-06-13
 */
@Service
public class DriverAuthMaterialServiceImpl extends ServiceImpl<DriverAuthMaterialMapper, DriverAuthMaterial> implements IDriverAuthMaterialService {
    @Autowired
    private IDriverService driverService;
    @Autowired
    private IDriverMaterialAuthLogService driverMaterialAuthLogService;
    @Autowired
    private LoginApi loginApi;

    /**
     * 1.实名材料的申请
     * 2.先进行参数的判断；如手机号，格式，邮箱等
     * 3.判断条件，判断是否已经通过实名或者是否已经有实名申请
     * 4.身份信息的真实性效验；可用第三方接口
     * 5.填写的实名材料
     * 6.实名材料的状态； 审核中
     * 7.司机的位状态；添加为审核中
     * @param dto 为实名材料
     */
    @Override
    public void apply(AuthApplyMaterialDto dto) {
        //2.先进行参数的判断；如手机号，格式，邮箱等
        AssertUtil.isPhone(dto.getPhone(),"手机号验证错误");


        //3.判断条件，判断是否已经通过实名或者是否已经有实名申请,
        //3.1先拿用户ID
        long logId = StpUtil.getLoginIdAsLong();
        Driver byId = driverService.getById(logId);
        //3.2判断不是，如果是则已申请
        AssertUtil.isFalse(BitStatesUtils.hasState(byId.getBitState(),BitStatesUtils.OP_REAL_AUTHENTICATING),"已申请");
        //3.3判断不是，如果是则已实名认证
        AssertUtil.isFalse(BitStatesUtils.hasState(byId.getBitState(),BitStatesUtils.OP_REAL_AUTHENTICATIONED),"已实名认证");

        //4.司机的位状态；添加为审核中
        long bitState = BitStatesUtils.addState(byId.getBitState(), BitStatesUtils.OP_REAL_AUTHENTICATING);
        //4.1修改位状态
        byId.setBitState(bitState);
        driverService.updateById(byId);

        //5.身份信息的真实性效验；可用第三方接口
        // 设置AK/SK认证
//        BasicCredentials provider = new BasicCredentials("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY");
//
//        // 初始化客户端
//        HcClient hcClient = new HcClient();
//        OcrClient ocrClient = new OcrClient(hcClient);
//        ocrClient.setCredentials(provider);
//
//        // 设置请求参数
//        RecognizeIdCardRequest request = new RecognizeIdCardRequest();
//        String base64Image = "base64_encoded_image_string"; // 这里替换为你的身份证图片的Base64编码字符串
//        request.withEnterpriseProjectId("").withBody(new IdCardRequestBody().withImage(base64Image).withSide("front"));
//
//        try {
//            // 发送请求并处理响应
//            RecognizeIdCardResponse response = ocrClient.recognizeIdCard(request);
//            System.out.println(response.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //6.填写的实名材料
        DriverAuthMaterial driverAuthMaterial = new DriverAuthMaterial();
        BeanUtils.copyProperties(dto, driverAuthMaterial);

        //7.实名材料的状态； 审核中
        driverAuthMaterial.setRealAuthStatus(Constants.Login.STATUS_APPLY);
        driverAuthMaterial.setCreateTime(new Date());
        driverAuthMaterial.setDriverId(logId);
        super.save(driverAuthMaterial);


    }
    /**
     * 实名认证的审核
     * 1.先进行参数判断，条件判断，只有是待审核状态的的才可以审核
     * 2.根据审核提交的材料ID查询实名的材料
     * 3.如果审核通过则修改状态为审核通过
     * 3.1修改司机的位状态，添加为实名通过
     * 3.2远程调用uaa设置司机的名字
     * 4.如果审核拒绝则修改状态为审核拒绝
     * 4.1修改实名中的位状态
     * 4.2设置审核人，审核时间，拒绝的备注，设置的修改时间
     * 4.3保存审核日志
     * 4.4给司机发送一个短信信息告知审核结果
     *
     */
    @Override
    public void audit(AuditParamDto dto) {
        //1.先进行参数判断，条件判断，只有是待审核状态的的才可以审核
        DriverAuthMaterial byId = super.getById(dto.getId());
        AssertUtil.isNotNull(byId,"非法参数请求");
        AssertUtil.isTrue(byId.getRealAuthStatus() == Constants.Login.STATUS_APPLY,"状态异常");

        //2.根据审核提交的材料ID查询实名的材料
        Driver byId1 = driverService.getById(byId.getDriverId());

        //2.2判断如果审核通过：
        if(dto.getApprove()){
            // 2.3.材料状态设置为：审核通过
            byId.setRealAuthStatus(Constants.Login.STATUS_SUCCESS);
            //2.4.修改司机位状态：添加实名通过
            long bitState = BitStatesUtils.addState(byId1.getBitState(), BitStatesUtils.OP_REAL_AUTHENTICATIONED);
            byId1.setBitState(bitState);
            //2.5.远程调用UAA,设置司机的名字
            JSONResult jsonResult = loginApi.update(LoginUpdate.builder().id(byId.getDriverId()).name(byId.getName()).build());
            AssertUtil.isTrue(jsonResult.isSuccess(),jsonResult.getMessage());
        }else{
            //4.如果审核拒绝则修改状态为审核拒绝
            byId.setRealAuthStatus(Constants.Login.STATUS_REJECT);
        }
        //4.1修改实名中的位状态
        long bitState = BitStatesUtils.removeState(byId1.getBitState(), BitStatesUtils.OP_REAL_AUTHENTICATING);
        byId1.setBitState(bitState);
        Date now = new Date();
        byId1.setUpdateTime(now);
        driverService.updateById(byId1);

        //4.2设置审核人，审核时间，拒绝的备注，设置的修改时间
        byId.setAuditRemark(dto.getRemark());
        byId.setAuditTime(now);
        byId.setAuditUserId(StpUtil.getLoginIdAsLong());
        byId.setUpdateTime(now);
        super.updateById(byId);

        //4.3保存审核日志
        driverMaterialAuthLogService.create(byId);

        //4.4给司机发送一个短信信息告知审核结果
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("https://utf8api.smschinese.cn/");
        //CD04C4C7EFF2C9F3EF19C05E0C877B7D
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
        NameValuePair[] data ={
                new NameValuePair("Uid", "hualishu"),
                new NameValuePair("Key", "CD04C4C7EFF2C9F3EF19C05E0C877B7D"),
                new NameValuePair("smsMob","18783106172"),
                new NameValuePair("smsText","验证码：8888")};
        post.setRequestBody(data);

        try {
            client.executeMethod(post);
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:"+statusCode); //HTTP状态码
            for(Header h : headers){
                System.out.println(h.toString());

            }
            String result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
            System.out.println(result);  //打印返回消息状态
            post.releaseConnection();
        }catch (Exception e){
            e.printStackTrace();
        }










    }




}
